<template>
  <!-- 视频生成第一步和第二步 -->
  <el-row :gutter="20">
    <el-col :span="24">
      <div class="themm-black themm-bg">
        <div class="step-text">
          step1:视频文案生成
        </div>
        <el-form :model="taskVideo" ref="taskVideo" size="small" :rules="rules" :hide-required-asterisk="true" :inline="true">
          <el-form-item label="视频主题：" prop="videoContent" label-width="100px">
            <el-input v-model="taskVideo.videoContent" placeholder="请输入视频主题" clearable style="width:600px" />
          </el-form-item>
          <el-form-item label="请选择受众：" prop="audienceId">
            <el-select v-model="taskVideo.audienceId" placeholder="请选择受众" clearable style="width: 100%">
              <el-option v-for="dict in audienceList" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="请选择策略或要素：" prop="strategyId">
            <el-select v-model="taskVideo.strategyId" @change="changeStrategy" placeholder="请选择策略" clearable style="width: 100%" :style="{opacity: taskVideo.strategyId ? 1 : .3}">
              <el-option v-for="dict in strategyList" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="或" prop="elementIds" label-width="30px">
            <el-select v-model="taskVideo.elementIds" collapse-tags @change="changeElement" multiple placeholder="请选择要素" clearable style="width: 100%" :style="{opacity: taskVideo.elementIds.length>0 ? 1 : .3}">
              <el-option v-for="dict in factorsList" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="请选择篇幅：" prop="length" label-width="110px">
            <el-select v-model="taskVideo.length" placeholder="请选择篇幅" clearable style="width: 100%">
              <el-option v-for="dict in dict.type.text_length" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="请选择语言：" prop="language">
            <el-select v-model="taskVideo.language" placeholder="请选择语言" clearable style="width: 100%"  @change="changeAudioConfig">
              <el-option v-for="dict in dict.type.language" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="primary-btn" size="mini" @click="createVideoText">生成视频文案</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-col>
    <el-col class="themm-black">
      <el-input :rows="15" v-model="taskVideo.dialogue" type="textarea" placeholder="请输入" />
    </el-col>
    <el-col class="themm-black">
      <div class="step-text">
        step2:语音生成
      </div>
      <!-- <button @click="playOrPause">{{ isPlaying ? '暂停' : '播放' }}</button>
        <audio ref="music" :src="curAudio" loop></audio> -->
      <div class="voice-select">
        <div class="swiper-container">
          <div class="swiper-wrapper">
            <div v-for="(item, index) in audioTemplate" :key="item.id" class="swiper-slide">
              <div class="swiper-content">
                <img class="voice-img" :src="item.thumbnail" alt="">
                <div class="right-content">
                  <audio :ref="'music' + index" :key="item.id" :src="item.url" loop></audio>
                  <div class="title" style="padding-right: 10px; flex: 1;">
                    <div class="voice-name ellipsis" style="width: 90%;">{{ item.description }}</div>
                    <!-- <div class="voice-desc">{{ item.description }}</div> -->
                  </div>
                  <div class="voice-play" @click="playVoice(item, index)">{{ item.isPlaying ? '暂停' : '试听' }}</div>
                </div>
              </div>
              <div class="voice-btn" :class="{ 'active': taskVideo.audioId==item.id }"  @click="handleSelect(item)">选择</div>
            </div>
          </div>
        </div>
        <div class="swiper-button-next"></div>
        <div class="swiper-button-prev"></div>
      </div>
    </el-col>
    <el-col>
      <div class="volume-list">
        <div class="volume-item">
          <span class="demonstration">语音音量</span>
          <div style="width: 300px;">
            <el-slider v-model="audioConfig.louderRatio" :min="1" :max="100"></el-slider>
          </div>
          <el-input-number size="small" v-model="audioConfig.louderRatio" controls-position="right" :min="1"
            :max="100"></el-input-number>
        </div>
        <div class="volume-item">
          <span class="demonstration">语音音调</span>
          <div style="width: 300px;">
            <el-slider v-model="audioConfig.sdpRatio" :disabled="!RegExp(/zh/).exec(taskVideo.language)" :min="0" :max="100"></el-slider>
          </div>
          <el-input-number size="small" :disabled="!RegExp(/zh/).exec(taskVideo.language)" v-model="audioConfig.sdpRatio" controls-position="right" :min="0"
            :max="100"></el-input-number>
        </div>
        <div class="volume-item">
          <span class="demonstration">语音音速</span>
          <div style="width: 300px;">
            <el-slider v-model="audioConfig.lengthScale" :min="1" :max="100"></el-slider>
          </div>
          <el-input-number size="small" v-model="audioConfig.lengthScale" controls-position="right" :min="1"
            :max="100" :step="1" step-strictly></el-input-number>
        </div>
      </div>
    </el-col>
    <el-col :span="24">
      <div class="volume-footer">
        <el-button type="primary" class="reset-btn" size="mini" @click="resetform">重置当前</el-button>
        <el-button type="primary" class="reset-btn" size="mini" @click="createVoice">生成语音</el-button>
        <!-- <el-button type="primary" class="reset-btn" size="mini" @click="auditionVoice">试听语音</el-button> -->
        <el-button type="primary" class="green-btn" size="mini" @click="handleDownload">导出语音文件</el-button>
        <el-button type="primary" :disabled="taskVideo.sequence.length==0" class="primary-btn" size="mini" @click="createNext">下一步</el-button>
      </div>
    </el-col>
  </el-row>
</template>

<script>
import Swiper from 'swiper';
import 'swiper/css/swiper.min.css'
import { getFileTemplate } from "@/api/content/task";
import { getAudienceAllList } from "@/api/library/audience";//受众接口表
import { getStrategyList } from "@/api/library/strategy";//策略接口表
import { getFactorsList } from "@/api/library/factors";//心里要素接口表
import { createVideosGenerationText, videoGenerationAudio } from "@/api/content/algorithm";//算法接口表
import axios from 'axios';
import JSZip from 'jszip';
import FileSaver from 'file-saver'
export default {
  name: "Step1",
  dicts: ['sys_normal_disable', 'text_length', 'language'],
  props: ['taskVideo'],
  data() {
    var checkStrategt = (rule, value, callback) => {
      console.log(value,this.taskVideo.elementIds,'asdasd')
      setTimeout(() => {
        if (!value && !this.taskVideo.elementIds) {
          callback(new Error('请选择策略'));
        } else {
          callback();
        }
      }, 500);
    };
    var checkElement = (rule, value, callback) => {
      setTimeout(() => {
        if (!value && !this.taskVideo.strategyId) {
          callback(new Error('请选择心理要素'));
        } else {
          callback();
        }
      }, 500);
    };
    return {
      loading: true,
      // form: {
      //   language:"CH"
      // },
      retrieveList: [],
      tabIndex: 'private',
      volumeNum: 1,
      swiper: null,
      audienceList: [],
      strategyList: [],
      factorsList: [],
      audioTemplate: [],//音频模板
      isPlaying: false,
      curAudio: {},//当前音频
      workDir: "",
      audioConfig: {
        text: '',
        louderRatio: 20,
        lengthScale: 1,
        sdpRatio: 0,
      },
      curAudio: {},//当前音频
      rules: {
        videoContent: [
          { required: true, message: '请输入视频主题', trigger: 'blur' },
        ],
        audienceId: [
          { required: true, message: '请选择受众', trigger: 'blur' },
        ],
        strategyId: [
          { validator: checkStrategt, trigger: 'blur' }
        ],
        elementIds: [
          { validator: checkElement, trigger: 'blur' }
        ],
        length: [
          { required: true, message: '请选择篇幅', trigger: 'blur' },
        ],
        language: [
          { required: true, message: '请选择语言', trigger: 'blur' },
        ],
      }
    };
  },
  watch: {
    taskVideo(val) {
      console.log(val,'val');
      if(val.audioConfig){
        this.audioConfig = val.audioConfig
      }
    }
  },
  mounted() {
  },
  methods: {
    init() {
      this.getAudioTemplate()
      this.getAudienceList()
      this.getStrategyList()
      this.getFactorsList()
    },
    playOrPause() {
      const audio = this.$refs.music;
      if (this.isPlaying) {
        audio.pause();
        this.isPlaying = false;
      } else {
        audio.play();
        this.isPlaying = true;
      }
    },
    // 选择策略
    changeStrategy(){
      this.$set(this.taskVideo,'elementIds',[])
    },
    // 选择要素
    changeElement(){
      this.taskVideo.strategyId = null
    },
    // 获取受众列表
    async getAudienceList() {
      const { data: res } = await getAudienceAllList(this.query);
      this.audienceList = res;
      this.$set(this.taskVideo,'audienceId',this.audienceList[0].id)
      this.$set(this.taskVideo,'language',this.dict.type.language[0].value)
    },
    // 获取策略列表
    async getStrategyList() {
      const { data: res } = await getStrategyList(this.query);
      this.strategyList = res;
      this.$set(this.taskVideo,'strategyId',this.strategyList[0].id)
    },
    // 获取心里要素列表
    async getFactorsList() {
      const { data: res } = await getFactorsList(this.query);
      this.factorsList = res;
    },
    // 获取音频模板
    async getAudioTemplate() {
      const { data: res } = await getFileTemplate('audios');
      console.log(res);
      this.audioTemplate = res.map(n => {
        n.isPlaying = false;
        return n;
      });
      this.getSwiper()
    },
    // 试听
    async playVoice(item, index) {
      const findex = this.audioTemplate.findIndex(i => i.isPlaying);
      if (findex !== -1 && findex !== index) {
        console.log(findex, '暂停上一个');
        const audios = this.$refs['music' + findex][0];
        audios.pause();
        this.audioTemplate[findex].isPlaying = false;
      }
      const audio = this.$refs['music' + index][0];
      console.log(item.isPlaying, '播放状态');
      if (item.isPlaying) {
        console.log('pause');
        audio.pause();
        item.isPlaying = false;
      } else {
        console.log('play');
        audio.play();
        this.curAudio = item;
        item.isPlaying = true;
      }

    },

    // 生成视频文案
    async createVideoText() {
      this.taskVideo.elementId = this.taskVideo.elementIds?this.taskVideo.elementIds.join(','):''
      this.$refs["taskVideo"].validate(valid => {
        if (valid) {
          this.openLoading();
          createVideosGenerationText(this.taskVideo).then(res=>{
            console.log(res.data);
            this.$message.success("视频文案生成成功");
            this.$modal.closeLoading();
            // const dialogue = res.data.dialogue || '';
            // const newText = dialogue.split('\n').filter(n => n).join('\n◈')
            // console.log(newText);
            // this.taskVideo.dialogue = '◈' +  newText;
            this.taskVideo.dialogue = res.data.dialogue || '';
            this.audioConfig.text = res.data.videoContent
          }).catch(err=>{
            this.$modal.closeLoading();
          })
          
        }
      });
    },
    // 生成语音
    async createVoice() {
      if (!this.taskVideo.dialogue) {
        this.$message.error("请先生成视频文案");
        return;
      }
      const params = {
        ...this.taskVideo,
        audioConfig: this.audioConfig
      }

      this.$refs["taskVideo"].validate(valid => {
        if (valid) {
          console.log(params, '语音生成入参')
          this.openLoading();
          videoGenerationAudio(params).then(res=>{
            console.log(res);
            this.$message.success("语音生成成功");
            this.$modal.closeLoading();
            const sequence = res?.data?.sequence || []
            sequence.forEach(item => {
              if (!item.clips) {
                item.clips = []
              }
            })
            this.taskVideo.sequence = sequence
          }).catch(err=>{
            console.log(err);
            this.$modal.closeLoading();
          })
          
        }
      });

    },
    // 试听语音
    auditionVoice() {

    },
    getSwiper() {
      console.log(this.swiper, '我来了');
      this.swiper = new Swiper(".swiper-container", {
        loop: false, // 无缝
        // autoplay: { //自动开始
        //     delay: 3000, //时间间隔
        //     disableOnInteraction: false, //*手动操作轮播图后不会暂停*
        // },
        autoplay: false,
        paginationClickable: true,
        slidesPerView: 5, // 一组三个
        spaceBetween: 15, // 间隔
        // 如果需要前进后退按钮
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev',
        },
        // 窗口变化,重新init,针对F11全屏和放大缩小,必须加
        observer: true,
        observeParents: true,
        // 如果需要分页器
        pagination: {
          el: '.swiper-pagination',
          clickable: true, // 分页器可以点击
        },
      })
    },
    // 下一步
    createNext() {
      // this.taskVideo.sequence = [
      //   {
      //     clips: [
      //       {
      //         start: 0,
      //         end: 10,
      //         url: this.taskVideo.audio,
      //         id: this.taskVideo.audioId
      //       }
      //     ]
      //   }
      // ]
      if(!this.taskVideo.sequence){
        return this.$message.error('请先生成语音')
      }

      console.log(this.taskVideo.sequence)
      this.$emit('changeStep', 2)
    },
    // 选择语音
    handleSelect(item) {
      console.log(item)
      this.taskVideo.audioId = item.id;
      this.taskVideo.audio = item.url;
    },
    // 打开加载层
    openLoading() {
      this.$modal.loading("正在生成，请稍候！");
    },
    // 选择语言
    changeAudioConfig(){
      this.audioConfig.sdpRatio = 0
    },
    // 重置当前
    resetform(){
      this.audioConfig = {
        text: '',
        louderRatio: 20,
        lengthScale: 1,
        sdpRatio: 0,
      }
      this.$emit("resetform");
      
      // this.resetForm("taskVideo");
    },
    // 语音文件导出
    getFileData (fileUrl) {
      return new Promise((resolve, reject) => {
        axios(fileUrl, {
            method: 'GET',
            responseType: 'blob'  // 返回的数据会被强制转为blob类型 ，转换成arraybuffer 也行
        }).then((res) => {
            console.log('res', res)
            resolve(res)
        }).catch(error => {
            reject(error)
        })
      })
    },
    async handleDownload() {
      const _this = this;
      _this.$modal.loading("正在导出，请稍候！");;
      const sequence = this.taskVideo.sequence || [];

      const zip = new JSZip() // 创建实例对象
      const promises = []
      sequence.forEach((item) => {
        const promise = this.getFileData(item.audio).then((res) => {
            const fileName = item.audio.split('/').pop()
            zip.file(fileName, res.data, {binary: true})
        })
        promises.push(promise)
        console.log(promises)
      })
      // 生成 zip 文件
      Promise.all(promises).then(() => {
        // 生成zip 文件
        zip.generateAsync({
          type: 'blob',
          compression: 'DEFLATE',  // STORE: 默认不压缩， DEFLATE：需要压缩
          compressionOptions: {
            level: 9          // 压缩等级 1~9   1 压缩速度最快， 9 最优压缩方式
          }
        }).then((res) => {
          FileSaver.saveAs(res, '语音文件.zip') // 使用FileSaver.saveAs保存文件，文件名可自定义
        }).finally(() => {
          this.$modal.closeLoading()
        })
      })
    }
  }
}
</script>
<style scoped lang="scss">
.step-text {
  color: #fff;
  font-size: 14px;
  padding: 20px;
}

.voice-select {
  padding: 0 65px;
  position: relative;
}

.swiper-slide {
  background: rgba(255, 255, 255, .1);
  border-radius: 8px;
}

.swiper-content {
  display: flex;
  color: #fff;
  padding: 15px;

  .voice-img {
    width: 64px;
    height: 64px;
    border-radius: 8px;
  }

  .right-content {
    display: flex;
    flex: 1;
    padding: 0 0 0 15px;
    align-items: center;
    justify-content: space-between;

    .voice-name {
      font-size: 15px;
      margin-bottom: 10px;
    }

    .voice-desc {
      font-size: 12px;
      color: rgba(255, 255, 255, .6);
      height: 40px;
      font-size: 14px;
      margin-bottom: 10px;
      word-break: break-all;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }

    .voice-play {
      width: 70px;
      height: 25px;
      line-height: 25px;
      text-align: center;
      background: rgba(0, 87, 255, 1);
      border-radius: 30px;
      cursor: pointer;
    }
  }
}

.voice-btn {
  background: rgba(255, 255, 255, .1);
  color: #fff;
  padding: 10px;
  border-radius: 0 0 8px 8px;
  font-size: 14px;
  text-align: center;
  cursor: pointer;
}
.voice-btn.active{
  background: rgba(0, 87, 255, 1);
}

.swiper-button-next,
.swiper-button-prev {
  background: rgba(255, 255, 255, .1);
  border-radius: 8px;
  color: #fff;
  font-size: 14px;
  padding: 73px 25px;
  top: 24px;
  opacity: 1;
  right: 0;
  &.swiper-button-disabled {
    background: rgba(255, 255, 255, 0.3);
    color: gray;
  }
}

.swiper-button-prev {
  left: 0;
}

.swiper-button-next:after,
.swiper-button-prev:after {
  font-size: 18px;
}

.volume-list {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;
  background: rgba(255, 255, 255, .1);
  padding: 10px 20px;
  border-radius: 12px;
  color: #fff;

  .volume-item {
    display: flex;
    align-items: center;
  }

  .demonstration {
    font-size: 14px;
    margin-right: 10px;
  }
}

.volume-footer {
  display: flex;
  justify-content: flex-end;
  background: rgba(255, 255, 255, .1);
  margin-top: 20px;
  padding: 20px;
  margin-left: -30px;
  margin-right: -30px;
}

.app-container {
  padding-bottom: 0;
}

.bg {
  background-image: url("../../../../assets/images/content_bg.png");
  background-size: 25%;
  background-repeat: no-repeat;
  background-position: top right;
}

::v-deep {
  .el-input-number--small {
    height: 32px;
    width: 50px;
    background: transparent;
    margin: 0 20px;
  }

  .themm-black .el-textarea__inner {
    border: none !important;
  }

  .el-input-number.is-controls-right .el-input__inner {
    background: rgba(255, 255, 255, .1);
    border: none;
    padding: 0 !important;
    color: #fff;
  }

  .el-input-number__increase,
  .el-input-number__decrease {
    background: rgba(255, 255, 255, .1);
    border: none !important;
    width: 20px;
    right: -25px !important;
    color: #fff;
  }

  .el-slider__bar {
    height: 4px;
    background: rgba(255, 255, 255, 1);
  }

  .el-slider__runway {
    background: rgba(255, 255, 255, .4);
    height: 4px;
  }

  .el-slider__button {
    width: 10px;
    height: 10px;
    border: none;
    margin-bottom: 3px;
  }
}
</style>
